<template>
  <view class="positions-page">
    <!-- 顶部导航栏占位 -->
    <view class="header-placeholder"></view>
    
    <!-- 当前持仓内容 -->
    <view class="content-wrapper">
      <!-- 总览卡片 -->
      <view class="overview-card">
      <view class="overview-header">
        <text class="overview-title">投资组合总览</text>
        <view class="info-icon" @click="showValueTip">
          <text class="icon">ℹ️</text>
        </view>
      </view>

      <view class="overview-grid">
        <view class="metric-item">
          <text class="metric-label">总市值</text>
          <text class="metric-value">¥{{ formatCurrency(overview.totalValue) }}</text>
          <!-- <text class="metric-time">{{ overview.lastUpdate }}</text> -->
        </view>

        <view class="metric-item">
          <text class="metric-label">总盈亏</text>
          <text class="metric-value" :class="overview.totalPnL >= 0 ? 'profit' : 'loss'">
            {{ overview.totalPnL >= 0 ? '+' : '' }}{{ formatCurrency(overview.totalPnL) }}
          </text>
          <!-- <text class="metric-rate" :class="overview.totalPnLRate >= 0 ? 'profit' : 'loss'">
            {{ overview.totalPnLRate >= 0 ? '+' : '' }}{{ overview.totalPnLRate.toFixed(2) }}%
          </text> -->
        </view>

        <view class="metric-item">
          <text class="metric-label">总成本</text>
          <text class="metric-value">¥{{ formatCurrency(overview.totalCost) }}</text>
        </view>

        <view class="metric-item">
          <text class="metric-label">收益率</text>
          <text class="metric-value" :class="overview.totalReturn >= 0 ? 'profit' : 'loss'">
            {{ overview.totalReturn >= 0 ? '+' : '' }}{{ overview.totalReturn.toFixed(2) }}%
          </text>
        </view>
      </view>
    </view>



    <!-- 持仓列表 -->
    <view class="positions-section">
      <view class="section-header">
        <text class="section-title">持仓明细</text>
        <view class="add-button" @click="addTrade">
          <text class="add-icon">+</text>
        </view>
      </view>

      <scroll-view class="positions-list" scroll-y>
        <view
          v-for="(position, index) in positions"
          :key="position.id"
          class="position-card"
          @click="viewPositionDetail(position)"
        >
          <view class="position-header">
            <view class="symbol-info">
              <text class="symbol-name">{{ position.symbolName }}</text>
              <text class="symbol-code">{{ position.symbolCode }}</text>
            </view>
            <view class="account-info">
              <text class="account-name">{{ position.accountName }}</text>
            </view>
          </view>

          <view class="position-metrics">
            <view class="metric-item">
              <text class="metric-label">市值</text>
              <text class="metric-value">¥{{ formatCurrency(position.marketValue) }}</text>
            </view>
            <view class="metric-item">
              <text class="metric-label">盈亏</text>
              <text class="metric-value" :class="position.unrealizedPnL >= 0 ? 'profit' : 'loss'">
                {{ position.unrealizedPnL >= 0 ? '+' : '' }}{{ formatCurrency(position.unrealizedPnL) }}
              </text>
              <view class="percentage-badge" :class="position.unrealizedPnLRate >= 0 ? 'profit' : 'loss'">
                <text class="percentage-text">{{ position.unrealizedPnLRate >= 0 ? '+' : '' }}{{ position.unrealizedPnLRate.toFixed(2) }}%</text>
              </view>
            </view>
          </view>

          <view class="position-actions">
            <view class="action-button" @click.stop="addTrade(position)">
              <text class="action-text"  >添加交易</text>
            </view>
            <view class="action-button primary" @click.stop="viewPositionDetail(position)">
              <text class="action-text">查看详情</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="positions.length === 0" class="empty-state">
          <image class="empty-icon" src="/static/empty.png" mode="aspectFit"></image>
          <text class="empty-text">暂无持仓记录</text>
          <view class="add-first-button" @click="addTrade">
            <text class="add-first-text">添加第一个交易</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</view>
</template>

<script>
import { baseGet } from '../../utils/api';
import { API_BASE_URL } from '../../utils/config';

export default {
  // 计算属性
  computed: {
    
  },

  // 数据定义
  data() {
    return {
      // 总览数据
      overview: {
        totalValue: 0,
        totalPnL: 0,
        totalPnLRate: 0,
        totalCost: 0,
        totalReturn: 0,
        lastUpdate: '2024/01/15 14:30'
      },

      // 持仓列表
      positions: []
    }
  },

  onLoad() {
    this.loadData()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadData()
    uni.stopPullDownRefresh()
  },

  methods: {
    // 加载数据
    async loadData() {
      try {
        // 显示加载提示
        uni.showLoading({ title: '加载中' });
        
        // 从API获取投资历史数据
        const res = await baseGet('/investment-history');
        
        if (res.statusCode === 200 && res.data.success) {
          const investmentHistory = res.data.data;
          
          // 计算各类别资产总和
          this.updatePositionsFromHistory(investmentHistory);
          
          // 更新资产分布数据
          this.updateDistributionData();
          
          // 更新总览数据
          this.updateOverview();
        } else {
          // 如果API获取失败，使用模拟数据
          this.loadMockData();
          uni.showToast({
            title: res.data?.error || '获取数据失败，使用模拟数据',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取投资历史数据失败:', error);
        // 网络错误时使用模拟数据
        this.loadMockData();
        if (error.message !== '未登录') {
          uni.showToast({
            title: '网络错误，使用模拟数据',
            icon: 'none'
          });
        }
      } finally {
        // 隐藏加载提示
        uni.hideLoading();
      }
    },



    // 加载模拟数据
    loadMockData() {
      // 总览数据保持不变
      this.overview = {
        totalValue: 156890.50,
        totalPnL: 12890.50,
        totalPnLRate: 8.92,
        totalCost: 144000.00,
        totalReturn: 8.95,
        lastUpdate: '2024/01/15 14:30'
      }

      // 持仓数据调整为按投资类别展示
      this.positions = [
        {
          id: 1,
          symbolName: '余额宝',
          symbolCode: '货币基金',
          accountName: '支付宝',
          marketValue: 50000.00,
          unrealizedPnL: 1200.00,
          unrealizedPnLRate: 2.45,
          category: '货币基金'
        },
        {
          id: 2,
          symbolName: '黄金ETF',
          symbolCode: '黄金',
          accountName: '招商银行',
          marketValue: 35890.50,
          unrealizedPnL: 3890.50,
          unrealizedPnLRate: 12.15,
          category: '黄金'
        },
        {
          id: 3,
          symbolName: '定存',
          symbolCode: '定存',
          accountName: '银行',
          marketValue: 45000.00,
          unrealizedPnL: 0,
          unrealizedPnLRate: 2.60,
          category: '定存'
        },
        {
          id: 4,
          symbolName: '比特币',
          symbolCode: '虚拟币',
          accountName: '数字钱包',
          marketValue: 26000.00,
          unrealizedPnL: 7800.00,
          unrealizedPnLRate: 42.35,
          category: '虚拟币'
        }
      ]

  
    },
    
    // 根据投资历史数据更新持仓列表
    updatePositionsFromHistory(historyData) {
      // 按类别分组并计算总和
      const categorySums = {};
      
      historyData.forEach(item => {
        if (!categorySums[item.category]) {
          categorySums[item.category] = 0;
        }
        categorySums[item.category] += item.cny;
      });
      
      // 创建新的持仓列表
      this.positions = Object.keys(categorySums).map((category, index) => {
        const marketValue = categorySums[category];
        // 这里为了演示，使用了简单的逻辑计算盈亏，实际应用中可能需要更复杂的计算
        const pnlRate = this.getCategoryPnlRate(category);
        const pnl = marketValue * pnlRate / 100;
        
        return {
          id: index + 1,
          symbolName: this.getCategorySymbolName(category),
          symbolCode: category,
          accountName: this.getCategoryAccountName(category),
          marketValue: marketValue,
          unrealizedPnL: pnl,
          unrealizedPnLRate: pnlRate,
          category: category
        };
      });
    },
    
    // 根据类别获取预估收益率（实际应用中应该从后端获取）
    getCategoryPnlRate(category) {
      const rateMap = {
        '货币基金': 2.45,
        '黄金': 12.15,
        '定存': 2.60,
        '虚拟币': 42.35,
        '基金': 8.50,
        '股票': 15.20
      };
      return rateMap[category] || 0;
    },
    
    // 根据类别获取显示名称
    getCategorySymbolName(category) {
      const nameMap = {
        '货币基金': '余额宝',
        '黄金': '黄金ETF',
        '定存': '定存',
        '虚拟币': '比特币',
        '基金': '指数基金',
        '股票': '股票'
      };
      return nameMap[category] || category;
    },
    
    // 根据类别获取账户名称
    getCategoryAccountName(category) {
      const accountMap = {
        '货币基金': '支付宝',
        '黄金': '招商银行',
        '定存': '银行',
        '虚拟币': '数字钱包',
        '基金': '基金账户',
        '股票': '股票账户'
      };
      return accountMap[category] || '其他账户';
    },
    

    
    // 更新总览数据
    updateOverview() {
      if (this.positions.length === 0) {
        this.overview = {
          totalValue: 0,
          totalPnL: 0,
          totalPnLRate: 0,
          totalCost: 0,
          totalReturn: 0,
          lastUpdate: new Date().toLocaleString('zh-CN')
        };
        return;
      }
      
      // 计算总市值和总盈亏
      const totalValue = this.positions.reduce((sum, position) => sum + position.marketValue, 0);
      const totalPnL = this.positions.reduce((sum, position) => sum + position.unrealizedPnL, 0);
      const totalCost = totalValue - totalPnL;
      const totalPnLRate = totalCost > 0 ? (totalPnL / totalCost * 100) : 0;
      
      // 更新总览数据
      this.overview = {
        totalValue: totalValue,
        totalPnL: totalPnL,
        totalPnLRate: totalPnLRate,
        totalCost: totalCost,
        totalReturn: totalPnLRate, // 这里简化处理，实际可能需要不同的计算逻辑
        lastUpdate: new Date().toLocaleString('zh-CN')
      };
    },



    // 格式化货币
    formatCurrency(amount) {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    },

    // 显示市值提示
    showValueTip() {
      uni.showModal({
        title: '市值说明',
        content: '市值基于您录入的最后成交价计算，非实时行情',
        showCancel: false,
        confirmText: '知道了'
      })
    },



    // 添加交易
    addTrade(position = null) {
      // 跳转到添加交易页面，并传递投资类别参数
      const url = position && position.category ? 
        `/pages/history/add?category=${encodeURIComponent(position.category)}` : 
        '/pages/history/add';
      
      uni.navigateTo({
        url: url
      })
    },

    // 查看持仓详情（跳转到历史投资页面并筛选对应类别）
    viewPositionDetail(position) {
      // 因为history是tabBar页面，需要使用switchTab跳转
      // 先将category参数存储到本地存储中
      // 确保传递的类别名称与后端数据匹配
      let category = position.category;
      // 处理特殊情况：比特币和余额宝等特定名称
      if (position.symbolName.includes('比特币')) {
        category = '加密货币';
      } else if (position.symbolName.includes('余额宝')) {
        category = '货币基金';
      }
      
      uni.setStorageSync('selectedCategory', category);
      
      // 使用switchTab跳转到history页面
      uni.switchTab({
        url: '/pages/history/history'
      })
    },
    

  }
}
</script>

<style scoped>
/* 全局样式 */
.positions-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部导航栏占位，适配小程序导航栏 */
.header-placeholder {
  height: 44px;
  background-color: #fff;
}

/* 内容容器样式 */
.content-wrapper {
  padding: 12px;
}

/* 总览卡片 - 优化样式 */
.overview-card {
  background: linear-gradient(135deg, #007AFF, #0056CC);
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
  color: white;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.overview-title {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.info-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  transition: background 0.3s;
}

.info-icon:active {
  background: rgba(255, 255, 255, 0.3);
}

.overview-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.metric-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.metric-label {
  font-size: 12px;
  color: white;
}

.metric-value {
  font-size: 18px;
  font-weight: 700;
  color: white;
}

.metric-time {
  font-size: 10px;
  color: white;
}

.metric-rate {
  font-size: 12px;
  font-weight: 500;
}

.profit {
    color: #52c41a; /* 正数绿色 */
  }

  .loss {
    color: #ff4d4f; /* 负数红色 */
  }

  .percentage-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    text-align: center;
    margin-top: 2px;
    background-color: red;
  }

  .percentage-text {
    font-size: 12px;
    font-weight: 500;
    color: white;
  }

/* 资产分布图 - 优化样式 */
.distribution-section {
  background: white;
  border-radius: 16px;
  padding: 12px;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 筛选器横向滚动 */
.filter-scroll {
  overflow-x: auto;
  margin-bottom: 12px;
  padding-bottom: 4px;
  -ms-overflow-style: none;
  scrollbar-width: none;
  width: 100%;
}

.filter-scroll::-webkit-scrollbar {
  display: none;
}

.filter-scroll > view {
  display: inline-block !important;
  margin-right: 8px;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 20px;
  background: #F5F5F5;
  font-size: 14px;
  color: #666;
  transition: all 0.2s;
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.filter-tab.compact {
  padding: 6px 12px;
  margin-right: 8px;
  font-size: 13px;
}

.filter-tab.active {
  background: #007AFF;
  color: white;
  box-shadow: 0 2px 6px rgba(0, 122, 255, 0.3);
}


/* 持仓列表 - 优化样式 */
.positions-section {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.add-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(0, 122, 255, 0.3);
  transition: all 0.3s;
}

.add-button:active {
  transform: scale(0.9);
  box-shadow: 0 1px 3px rgba(0, 122, 255, 0.3);
}

.add-icon {
  color: white;
  font-size: 20px;
  font-weight: bold;
}

.positions-list {
  max-height: 60vh;
}

.position-card {
  background: #F8F8F8;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  transition: all 0.2s;
  border: 1px solid #f0f0f0;
}

.position-card:active {
  background: #F0F0F0;
  transform: scale(0.98);
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.symbol-info {
  flex: 1;
}

.symbol-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: block;
}

.symbol-code {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.account-name {
  font-size: 12px;
  color: #999;
  background: white;
  padding: 4px 8px;
  border-radius: 12px;
}

.position-metrics {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
}

.position-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  flex: 1;
  padding: 10px 16px;
  border-radius: 8px;
  background: #F0F0F0;
  text-align: center;
  transition: all 0.2s;
}

.action-button.primary {
  background: #007AFF;
}

.action-button.primary .action-text {
  color: white;
}

.action-button:active {
  transform: scale(0.95);
}

.action-text {
  font-size: 13px;
  color: #666;
}

/* 空状态 - 优化样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

.add-first-button {
  padding: 12px 24px;
  background: #007AFF;
  border-radius: 24px;
  margin-top: 20px;
  box-shadow: 0 2px 6px rgba(0, 122, 255, 0.3);
  transition: all 0.3s;
  display: inline-block;
}

.add-first-button:active {
  transform: scale(0.95);
  box-shadow: 0 1px 3px rgba(0, 122, 255, 0.3);
}

.add-first-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}
.position-metrics .metric-value {
  color: #333;
}
</style>
